package com.kn.keywordmatch.task;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kn.keywordmatch.dto.req.MatchByKeywordReq;
import com.kn.keywordmatch.service.KeywordIndex;
import lombok.extern.slf4j.Slf4j;
import org.ahocorasick.trie.Emit;
import org.ahocorasick.trie.Trie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 拉取定向匹配方案列表
 */
@Component
@Slf4j
public class BuildKeywordIndexTask {

    @Value("${monitor.keyword.url}")
    private String getKeywordUrl;

    private final KeywordIndex keywordIndex; // 声明 KeywordIndex

    @Autowired
    public BuildKeywordIndexTask(KeywordIndex keywordIndex) {
        this.keywordIndex = keywordIndex; // 注入 KeywordIndex
    }

    @Scheduled(fixedRate = 60000) // 每隔60秒拉取数据
    public void buildKeywordIndex() {
        // 请求接口
        log.info("buildKeywordIndex.请求接口构建关键字倒排索引-开始执行");
        HttpRequest httpRequest = HttpUtil.createGet(getKeywordUrl + 0+"&createTime=" + "2025-05-29 22:20:00", true);
        HttpResponse httpResponse = httpRequest.execute();
        if (httpResponse != null && httpResponse.body() != null) {
            // 解析 JSON 并直接转换为 MatchByDirectionReq 对象列表
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            List<MatchByKeywordReq> keywordReqList = JSONUtil.parseArray(jsonObject.getStr("data")).toList(MatchByKeywordReq.class);
            // 构建倒排索引
            // 构建或更新倒排索引
            if(!keywordReqList.isEmpty()){
                keywordIndex.buildOrUpdateIndex(keywordReqList);
            }
            log.info("关键字倒排索引构建完成");
        } else {
            log.error("未能成功获取数据");

        }
    }





    public static void main(String[] args) {
        // 创建一个 Trie 实例
        Trie trie = Trie.builder()
                .addKeyword("刘虎和朋友们")
                .addKeyword("刘虎和朋友们 说说山西")
                .build();

        // 要匹配的文本
        String text = "刘虎和朋友们 说说山西";

        // 查找匹配的结果
        List<Emit> emits = (List<Emit>) trie.parseText(text);

        // 输出匹配结果
        for (Emit emit : emits) {
            System.out.println("Matched: " + emit.getKeyword());
        }
    }
}
